import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { message } from 'antd';
import { authService } from '../services/api';

interface User {
  id: number;
  username: string;
  email: string;
  avatar?: string;
  grade?: string;
  major?: string;
  dream_career?: string;
  bio?: string;
}

interface AuthContextType {
  user: User | null;
  token: string | null;
  isAuthenticated: boolean;
  login: (login: string, password: string) => Promise<boolean>;
  loginWithCode: (email: string, code: string) => Promise<boolean>;
  register: (userData: RegisterData) => Promise<boolean>;
  verifyEmail: (email: string, code: string) => Promise<boolean>;
  sendLoginCode: (email: string) => Promise<boolean>;
  logout: () => void;
  updateUser: (userData: Partial<User>) => void;
  loading: boolean;
  loginLoading: boolean;
  isInitializing: boolean;
}

interface RegisterData {
  username: string;
  email: string;
  password: string;
  grade?: string;
  major?: string;
  dream_career?: string;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

interface AuthProviderProps {
  children: ReactNode;
}

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);
  const [token, setToken] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [loginLoading, setLoginLoading] = useState(false);
  const [isInitializing, setIsInitializing] = useState(true);

  useEffect(() => {
    // 检查本地存储的token
    const storedToken = localStorage.getItem('token');
    if (storedToken) {
      setToken(storedToken);
      // 验证token有效性，添加超时处理
      const verifyPromise = authService.verifyToken(storedToken);
      const timeoutPromise = new Promise((_, reject) => 
        setTimeout(() => reject(new Error('验证超时')), 10000) // 10秒超时
      );
      
      Promise.race([verifyPromise, timeoutPromise])
        .then((response: any) => {
          if (response && response.user) {
            setUser(response.user);
          } else {
            // 如果响应格式不正确，清除token
            localStorage.removeItem('token');
            setToken(null);
          }
        })
        .catch((error) => {
          console.error('Token验证失败:', error);
          // 只有在明确是认证错误时才清除token
          if (error.message === '验证超时') {
            console.warn('Token验证超时，但保留token以便重试');
          } else {
            localStorage.removeItem('token');
            setToken(null);
          }
        })
        .finally(() => {
          setLoading(false);
          setIsInitializing(false);
        });
    } else {
      setLoading(false);
      setIsInitializing(false);
    }
  }, []);

  const login = async (login: string, password: string): Promise<boolean> => {
    console.log('AuthContext login 开始:', { login, password });
    setLoginLoading(true);
    try {
      const response = await authService.login(login, password) as any;
      console.log('AuthContext login 响应:', response);
      if (response.token) {
        setToken(response.token);
        setUser(response.user);
        localStorage.setItem('token', response.token);
        message.success('登录成功');
        console.log('AuthContext login 成功，返回true');
        return true;
      }
      console.log('AuthContext login 失败，没有token');
      return false;
    } catch (error: any) {
      console.log('AuthContext login 异常:', error);
      message.error(error.message || '登录失败');
      return false;
    } finally {
      setLoginLoading(false);
    }
  };

  const loginWithCode = async (email: string, code: string): Promise<any> => {
    setLoginLoading(true);
    try {
      const response = await authService.loginWithCode(email, code) as any;
      if (response.isNewUser) {
        // 新用户，不设置token，返回新用户标识
        return { success: true, isNewUser: true, email: response.email };
      } else if (response.token) {
        // 老用户，正常登录
        setToken(response.token);
        setUser(response.user);
        localStorage.setItem('token', response.token);
        message.success('登录成功！');
        
        // 不在这里设置初始化状态，让LoginPage的进度条控制
        return { success: true, isNewUser: false };
      }
      return { success: false };
    } catch (error: any) {
      message.error(error.message || '登录失败');
      return { success: false };
    } finally {
      setLoginLoading(false);
    }
  };

  const register = async (userData: RegisterData): Promise<boolean> => {
    try {
      await authService.register(userData);
      message.success('注册成功，请查收邮箱验证码');
      return true;
    } catch (error: any) {
      message.error(error.message || '注册失败');
      return false;
    }
  };

  const verifyEmail = async (email: string, code: string): Promise<boolean> => {
    try {
      await authService.verifyEmail(email, code);
      message.success('邮箱验证成功');
      return true;
    } catch (error: any) {
      message.error(error.message || '验证失败');
      return false;
    }
  };

  const sendLoginCode = async (email: string): Promise<boolean> => {
    try {
      await authService.sendLoginCode(email);
      message.success('验证码已发送，请查收邮箱');
      return true;
    } catch (error: any) {
      message.error(error.message || '发送失败');
      return false;
    }
  };

  const logout = () => {
    setUser(null);
    setToken(null);
    localStorage.removeItem('token');
    message.success('已退出登录');
  };

  const updateUser = (userData: Partial<User>) => {
    if (user) {
      setUser({ ...user, ...userData });
    }
  };

  const value: AuthContextType = {
    user,
    token,
    isAuthenticated: !!token,
    login,
    loginWithCode,
    register,
    verifyEmail,
    sendLoginCode,
    logout,
    updateUser,
    loading,
    loginLoading,
    isInitializing
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};
